package pattern.template;

import static oracle.jrockit.jfr.events.Bits.swap;

/**
 * 冒泡排序模板模式抽象类
 *
 * @author sun.ye
 * @since 2020-07-15 14:38
 */
public abstract class AbstractBubbleSorter {

    protected int operations;
    protected int length;

    protected int doSort() {
        operations = 0;
        if (length <= 1) {
            return operations;
        }
        for (int nextToLast = length - 2; nextToLast >= 0; nextToLast--) {
            for (int index = 0; index <= nextToLast; index++) {
                if (outOfOrder(index)) {
                    swap(index);
                }
                operations++;
            }
        }
        return operations;
    }
    protected abstract void swap(int index);
    protected abstract boolean outOfOrder(int index);
}